#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>

#define LEN 1024 //命令的最大的长度
#define NUM 32 //命令拆分后的最大个数
int main()
{
  char cmd[LEN];
  char* myargv[NUM];
  const char* user=getenv("USER");//获取用户名
  const char* path=getenv("PWD");//获取当前路径
  while(1)
  {
    printf("[%s@ %s]# ",user,path);
    fgets(cmd,LEN,stdin);
    cmd[strlen(cmd)-1]='\0';
    //分割解析命令
    int i=0;
    myargv[i++]=strtok(cmd," ");
    while(myargv[i]=strtok(NULL," ")) i++;
    if(fork()==0)
    {

      //子进程执行替换任务
      execvp(myargv[0],myargv);
      exit(1);
    }
    int status;
    int ret=waitpid(-1,&status,0);//回收资源
    if(ret==-1){
      perror("wait");
    }else{
      printf("exit code:%d\n", (status>>8)& 0xFF);
    }
  }
  return 0;
}
